package com.skateboard.reelviewtest.view.reelview;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Handler;
import android.os.Message;
import android.renderscript.Sampler;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;

import com.skateboard.reelviewtest.R;
import com.skateboard.reelviewtest.utils.SimpleUtils;
import com.skateboard.reelviewtest.view.particle.FireflyView;
import com.tenny.mystory.TextViewVertical;

/**
 * @作者： xuze
 * @时间： 2020/11/28 9:43 PM
 * @描述：
 */
public class ReelLayout extends ViewGroup implements View.OnClickListener {
    /**
     * 是否展开
     */
    private boolean isExpand;

    private ValueAnimator valueAnimator;
    private final static long duration=2000;

    private float reelViewLeftWidth=SimpleUtils.dp2px(getContext(),20);
    private float reelViewRightWidth=SimpleUtils.dp2px(getContext(),20);
    private float reelViewContentWidht=SimpleUtils.dp2px(getContext(),200);

    private HorizontalScrollView scrollView;
    private TextViewVertical tvVertical;
    private ImageView ivTitle;
    private FireflyView ivLeft;
    private FireflyView ivRight;


    private String str = "最开始的时候,你并不熟悉这座陌生的城市,你甚至摸得到内心那种无法融入的恐慌和彷徨,据说,这种感觉叫漂泊。皮卡丘！！！";
    private static final int printTextIntervalTime=100;

    private int  value=0;

    private ReelLayoutExpandCallback expandCallback;

    private ValueAnimator scrollValueAnimator;

    private boolean isDestory;
    private Handler handle= new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(isDestory){
                return;
            }
            if ((TextUtils.isEmpty(tvVertical.getText())||tvVertical.getText().length() - 1 < value)
                    &&!TextUtils.isEmpty(str)&&str.length()>value) {

                //处理平滑滚动
                handleScroll();
                String txt = str.substring(0, value + 1);
                tvVertical.setText(txt);
                value++;
            }
            if(value<str.length()){
                handle.sendEmptyMessageDelayed(0,printTextIntervalTime);
            }
            Log.e("sssss","==========handleMessage==");

        }
    };

    public ReelLayout(Context context) {
        this(context,null);
    }

    public ReelLayout(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public ReelLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init(){
        valueAnimator = ValueAnimator.ofFloat(0, 1).setDuration(duration);
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.setStartDelay(1000);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float mAnimatorValue = (float) animation.getAnimatedValue();
                Log.e("sssss","==========valueAnimator=="+mAnimatorValue);
                int width = (int) (mAnimatorValue * reelViewContentWidht);
                RelativeLayout.LayoutParams layoutParams= (RelativeLayout.LayoutParams) getLayoutParams();
                layoutParams.width= (int) (width+reelViewRightWidth+reelViewLeftWidth);
                setLayoutParams(layoutParams);
            }
        });
        valueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                if(isExpand){
                    startPrintText();
                }else{
                    endPrintText();
                }
                if(!isExpand){
                    ivLeft.stopAnimation();
                    ivRight.stopAnimation();
                }
            }

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                if(isExpand){
                    ivLeft.startAnimation();
                    ivRight.startAnimation();
                }
            }
        });
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        measureChildren(widthMeasureSpec,heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int width     = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode= MeasureSpec.getMode(heightMeasureSpec);
        int height    = MeasureSpec.getSize(heightMeasureSpec);

        if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST){
            int groupHeight= getReelLayoutHeight();
            setMeasuredDimension((int) (reelViewRightWidth+reelViewLeftWidth), groupHeight);
        }else if (widthMode == MeasureSpec.AT_MOST){
            setMeasuredDimension((int) (reelViewRightWidth+reelViewLeftWidth), height);
        }else if (heightMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(width, getReelLayoutHeight());
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if(getChildCount()>=3){
            View  leftView= getChildAt(1);
            View contentView = getChildAt(0);
            View rightView = getChildAt(2);
            int padTop=(leftView.getMeasuredHeight()-contentView.getMeasuredHeight())/2;
            contentView.layout((r-l-contentView.getMeasuredWidth())/2, padTop,
                    (r-l-contentView.getMeasuredWidth())/2+contentView.getMeasuredWidth(), contentView.getMeasuredHeight()+padTop);
            leftView.layout(0, 0,
                    leftView.getMeasuredWidth(), leftView.getMeasuredHeight());
            rightView.layout(r-l-rightView.getMeasuredWidth(), 0,r-l, rightView.getMeasuredHeight());
        }
    }

    private int getReelLayoutHeight(){
        int count = getChildCount();
        int totalHeight = 0;
        for (int i = 0 ; i < count ; i++){
            View view = getChildAt(i);
            if(view!=null){
                int currentWidth = view.getMeasuredHeight();
                if (totalHeight < currentWidth){
                    totalHeight = currentWidth;
                }
            }
        }
        return totalHeight;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        scrollView=findViewById(R.id.scrollview);
        tvVertical=findViewById(R.id.tvVertical);
        ivTitle=findViewById(R.id.iv_title);
        ivLeft=findViewById(R.id.ivLeft);
        ivRight=findViewById(R.id.ivRight);
        ivLeft.setOnClickListener(this);
        ivRight.setOnClickListener(this);
        tvVertical.setTotalText(str);
    }

    private void startPrintText(){
        ivTitle.setVisibility(View.VISIBLE);
        ivTitle.setAnimation(AnimationUtils.makeInAnimation(getContext(), false));
        tvVertical.setText("");
        value=0;
        handle.sendEmptyMessageDelayed(0,200);

        //================================
        if(scrollView.getChildCount()>0){
            View view =scrollView.getChildAt(0);
            int x=view.getMeasuredWidth();
            if(view!=null){
                scrollView.scrollTo(x,0);
            }
        }
    }
    private void endPrintText(){
        ivTitle.setVisibility(View.INVISIBLE);
        tvVertical.setText("");
        value=0;
    }

    public void startAnimation(){
        if(valueAnimator.isRunning()){
            return;
        }
        if(isExpand){
            valueAnimator.start();
        }else{
            valueAnimator.reverse();
        }
    }

    @Override
    public void onClick(View v) {
        if(valueAnimator.isRunning()){
            return;
        }
        isExpand=!isExpand;
        if(expandCallback!=null){
            expandCallback.expandCallback(isExpand);
        }
        startAnimation();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        handle.removeCallbacksAndMessages(null);
        isDestory=true;
        if(scrollValueAnimator!=null&&scrollValueAnimator.isRunning()){
            scrollValueAnimator.cancel();
        }

        if(valueAnimator!=null&&valueAnimator.isRunning()){
            valueAnimator.cancel();
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
    }

    public interface ReelLayoutExpandCallback{
        void expandCallback(boolean isExpand);
    }

    public void setExpandCallback(ReelLayoutExpandCallback expandCallback) {
        this.expandCallback = expandCallback;
    }

    private void handleScroll(){
        if(tvVertical==null){
            return;
        }
        //一屏 显示多少个字
        int textCountOfScreen = (tvVertical.getColNumOfScreen()-1)*tvVertical.getColWordCount();
        if(tvVertical.getText().length()>textCountOfScreen){
            if(scrollValueAnimator==null){
                if(scrollValueAnimator==null){
                    scrollValueAnimator=ValueAnimator.ofFloat(1,0).setDuration((str.length()-textCountOfScreen)*printTextIntervalTime);
                    scrollValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener(){

                        @Override
                        public void onAnimationUpdate(ValueAnimator animation) {
                            float totalScrollLength=(tvVertical.getTotalCol()-tvVertical.getColNumOfScreen())*tvVertical.getOneWordWidth();
                            float mAnimatorValue = (float) animation.getAnimatedValue();
                            int sctollToX= (int) (totalScrollLength*mAnimatorValue);
                            Log.e("ssssss","============scrollX:"+sctollToX);
                            scrollView.scrollTo(sctollToX,0);
                        }
                    });
                }
            }
            if(!scrollValueAnimator.isRunning()){
                scrollValueAnimator.start();
            }
        }
    }
}
